import { ElMessageBox, ElMessage } from 'element-plus';
import { cancelOrderX, delOrder, logisticsCancel } from '../api/platformOrders/orders/list';

// 通用物流操作 Hook
export function useLogisticsAction(refreshCallback: () => void) {
  const refresh = refreshCallback || (() => {});

  /**
   * 执行物流操作（拦截、取消发货、删除订单）
   * @param {Object} row - 订单行数据
   * @param {string} actionType - 操作类型: 'intercept' | 'cancel' | 'remove'
   */
  const execute = async (row: any, actionType: string) => {
    const params = {
      orderId: row.orderId,
      logisticsPlatformCode: row.logisticsPlatformCode,
      logisticsNo: row.logisticsNo,
      shippingType: row.shippingType
    };

    const messages: Record<string, any> = {
      intercept: {
        title: '拦截物流',
        content: '确定拦截物流吗？如拦截失败，请联系客户拒收。',
        success: '拦截物流指令已发出',
        apiFn: logisticsCancel,
        params
      },
      cancel: {
        title: '取消发货',
        content: '确定取消发货吗？',
        success: '取消发货成功',
        apiFn: cancelOrderX,
        params
      },
      remove: {
        title: '删除订单',
        content: '确定删除选中的订单吗？此操作不可撤销。',
        success: '订单删除成功',
        apiFn: delOrder,
        params: row.orderId
      }
    };

    const { title, content, success, apiFn, params: apiParams } = messages[actionType];

    try {
      // 打开确认框
      await ElMessageBox.confirm(content, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false,
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            try {
              await apiFn(apiParams);
              ElMessage.success(success);
              refresh();
              done(); // 关闭弹窗
            } catch (error) {
              console.error('操作失败:', error);
              ElMessage.error('操作失败，请稍后重试');
              instance.confirmButtonLoading = false; // 停止 loading
            }
          } else {
            done();
          }
        }
      });
    } catch (err) {
      // 用户点击了取消
      if (err !== 'cancel') {
        console.error('物流操作异常:', err);
      }
    }
  };

  return { execute };
}
